package com.csun.cmny.provider.service.impl;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.provider.exceptions.DmcBizException;
import com.csun.cmny.provider.model.constant.DeviceConstant;
import com.csun.cmny.provider.model.domain.DmcCsunGatewayWifi;
import com.csun.cmny.provider.model.domain.DmcDevice;
import com.csun.cmny.provider.model.dto.gateway.CsunGatewayWifiDto;
import com.csun.cmny.provider.service.DmcCsunGatewayWifiService;
import com.csun.cmny.provider.service.DmcDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
@Slf4j
@Transactional
public class DmcCsunGatewayWifiServiceImpl extends BaseService<DmcCsunGatewayWifi> implements DmcCsunGatewayWifiService {

   @Resource
   private DmcDeviceService dmcDeviceService;

    @Override
    public int setCsunGatewayWifi(CsunGatewayWifiDto csunGatewayWifiDto, LoginAuthDto loginAuthDto) {
        DmcDevice device = dmcDeviceService.selectByKey(csunGatewayWifiDto.getDeviceId());

        if(device == null){
            throw new DmcBizException(ErrorCodeEnum.DMC100610002,csunGatewayWifiDto.getDeviceId());
        }
        if(!device.getDeviceType().equals(DeviceConstant.CSUN_GATEWAY)){
            throw new DmcBizException(ErrorCodeEnum.DMC100614004);
        }

        //查询是否有该条wifi设置数据
        DmcCsunGatewayWifi dmcCsunGatewayWifi = selectByKey(csunGatewayWifiDto.getDeviceId());

        if(dmcCsunGatewayWifi == null){
            dmcCsunGatewayWifi = new DmcCsunGatewayWifi();
            BeanUtils.copyProperties(csunGatewayWifiDto,dmcCsunGatewayWifi);
            dmcCsunGatewayWifi.setId(csunGatewayWifiDto.getDeviceId());
            dmcCsunGatewayWifi.setUpdateInfo(loginAuthDto);
            return save(dmcCsunGatewayWifi);
        }else{
            BeanUtils.copyProperties(csunGatewayWifiDto,dmcCsunGatewayWifi);
            dmcCsunGatewayWifi.setId(csunGatewayWifiDto.getDeviceId());
            dmcCsunGatewayWifi.setUpdateInfo(loginAuthDto);
            return update(dmcCsunGatewayWifi);
        }
    }
}
